package console4.widgets;

import java.io.InputStream;
import java.util.concurrent.Semaphore;

import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.ScrolledComposite;
import org.eclipse.swt.custom.StyleRange;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;

import console4.util.InputStreamGobbler;

public class ConsoleTextPane {

	private StyledText textPane;
	private ScrolledComposite scrolledComposite;
	private Semaphore printSemaphore=new Semaphore(1);
	//dispose
	private Color backgroundColor=new Color(Display.getCurrent(),  0,  0,  0);
	private Color errorColor=	  new Color(Display.getCurrent(),255,  0,  0);
	private Color textColor=	  new Color(Display.getCurrent(),255,255,255);
	private Font  textFont =	  new Font(Display.getCurrent(), "Lucida Console", 12, SWT.NONE);

	public ConsoleTextPane(Composite parent) {
		textPane = new StyledText(parent, SWT.V_SCROLL | SWT.MULTI | SWT.WRAP);
		textPane.setEditable(false);
		textPane.setBackground(backgroundColor);
		textPane.setForeground(textColor);
		textPane.setFont(textFont);
		textPane.setMargins(4, 0, 0, 4);
		textPane.addDisposeListener(new DisposeListener() {
			@Override
			public void widgetDisposed(DisposeEvent e) {
				backgroundColor.dispose();
				textColor.dispose();
				errorColor.dispose();
				textFont.dispose();
			}
		});
	}

	public void setConsoleOutput(final InputStream inputStream) {
		new InputStreamGobbler(this,printSemaphore,inputStream,false).start();
	}
	
	public void addTextToPane(final String str, final boolean errorStream) {
		textPane.getDisplay().asyncExec(new Runnable() {
		    public void run() {
				if(errorStream)
					printError(str);
				else
					textPane.append(str);
				textPane.setTopIndex(Integer.MAX_VALUE);
		    }
		});
	};

	public void setConsoleErrorOutput(final InputStream errorStream) {
		new InputStreamGobbler(this,printSemaphore,errorStream,true).start();
	}

	public void setLayoutData(Object layoutData) {
		textPane.setLayoutData(layoutData);
	}

	public String getText() {
		return textPane.getText();
	}

	public StyleRange[] getTextLayout() {
		return textPane.getStyleRanges();
	}

	public void setOldText(TabSaveState tss) {		
		textPane.setText(tss.getText());
		for(int i=0;i<tss.getTextLayout().length;i+=2)
			textPane.setStyleRange(new StyleRange(tss.getTextLayout()[i], tss.getTextLayout()[i+1], errorColor, backgroundColor));
		textPane.setTopIndex(Integer.MAX_VALUE);
	}

	private void printError(String str) {
		int index=textPane.getText().length();
		textPane.append(str);
		textPane.setStyleRange(new StyleRange(index,str.length(),errorColor,backgroundColor));
	}

	public void scrollBy(int count) {
		textPane.setTopPixel(textPane.getTopPixel()-10*count);
	}
}
